package com.gzhu.knowledgeAdmin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzhu.knowledgeAdmin.common.constant.RoleType;
import com.gzhu.knowledgeAdmin.common.exception.BusinessException;
import com.gzhu.knowledgeAdmin.common.result.ErrorCode;
import com.gzhu.knowledgeAdmin.common.utils.UserInfoUtils;
import com.gzhu.knowledgeAdmin.common.vo.RoleVo;
import com.gzhu.knowledgeAdmin.dao.RoleMapper;
import com.gzhu.knowledgeAdmin.entity.*;
import com.gzhu.knowledgeAdmin.service.RolePermissionService;
import com.gzhu.knowledgeAdmin.service.RoleService;
import com.gzhu.knowledgeAdmin.service.UserRoleService;
import com.gzhu.knowledgeAdmin.service.XtyhService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-01-12
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private XtyhService xtyhService;

    //根据用户获取角色数据
    @Override
    public RoleVo findRoleByUserId(Integer userId) {

        Xtyh user = xtyhService.getById(userId);


        //查询所有的角色
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        User curUser = UserInfoUtils.getCurrentUser();
        if(curUser.getYhlx()== RoleType.ADMIN){
            // 公司管理员只能为员工分配自己公司的角色
            wrapper.eq("gs_id",curUser.getGsid());
        }

        // 根据用户的类型来查询相对应的角色
        wrapper.eq("role_code",user.getYhlx());
        List<Role> allRolesList =baseMapper.selectList(wrapper);



        //根据用户id，查询用户拥有的角色id
        UserRole userRole = userRoleService.getOne(new QueryWrapper<UserRole>().eq("user_id", userId).select("role_id"));



        RoleVo roleVo = new RoleVo();
        roleVo.setAssignRole(userRole==null?null:userRole.getRoleId());
        roleVo.setAllRolesList(allRolesList);
        return roleVo;
    }



    //根据用户分配角色
    @Override
    @Transactional
    public void saveUserRoleRealtionShip(Integer userId, String roleId) {

        // 先删除已有的分配记录
        userRoleService.remove(new QueryWrapper<UserRole>().eq("user_id", userId));

        // 再添加新的
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(roleId);
        userRoleService.save(userRole);

    }

    @Transactional
    @Override
    public void removeRoleById(String id) {

        // 先删除角色菜单表数据
        rolePermissionService.removeByRoleId(id);

        // 再删除角色用户表数据
        userRoleService.removeByRoleId(id);

        // 最后删除角色表数据
        baseMapper.deleteById(id);

    }

    @Override
    @Transactional
    public void removeBatchByRoleIds(List<String> idList) {
        // 先删除角色菜单表数据
        rolePermissionService.removeBatchByRoleIds(idList);

        // 再删除角色用户表数据
        userRoleService.removeBatchByRoleIds(idList);

        // 最后删除角色表数据
        baseMapper.deleteBatchIds(idList);
    }

    @Override
    public Page<Role> getPageList(Long page, Long limit, Role role) {
        Page<Role> pageParam = new Page<>(page, limit);


        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(role.getRoleName())) {
            wrapper.like("role_name", role.getRoleName());
        }

        // 根据操作对象不同，获取不同的角色
        User user = UserInfoUtils.getCurrentUser();
        if(user.getYhlx()==RoleType.SYS_ADMIN){
            wrapper.eq("role_code",2);
        }else if(user.getYhlx()==RoleType.ADMIN){
            // 公司管理员只能查看自己公司的角色
            wrapper.eq("role_code",3);
            wrapper.eq("gs_id",user.getGsid());
        }

        page(pageParam, wrapper);
        return pageParam;
    }

    @Override
    public void saveRole(Role role) {
        User user = UserInfoUtils.getCurrentUser();
        if(user.getYhlx()==RoleType.SYS_ADMIN){
            role.setRoleCode(RoleType.ADMIN);
        }else if(user.getYhlx()==RoleType.ADMIN){
            // 如果是公司管理员添加的角色，则指明该角色只属于本公司
            role.setRoleCode(RoleType.COMMON_USER);
            role.setGsId(user.getGsid());
        }
        save(role);
    }

    /**
     * 获取角色的菜单ID集合
     * @param roleId
     * @return
     */
    @Override
    public List<String> getRolePermissionIds(String roleId) {

        List<RolePermission> rolePermissionList = rolePermissionService.list(new QueryWrapper<RolePermission>().eq("role_id", roleId).select("permission_id"));
        return rolePermissionList.stream().map(RolePermission::getPermissionId).collect(Collectors.toList());
    }



}
